package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Banner;
import cn.wolfcode.query.BannerQuery;
import cn.wolfcode.repository.BannerRepository;
import cn.wolfcode.service.IBannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class BannerServiceImpl implements IBannerService {



    @Autowired
    private BannerRepository bannerRepository;
    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Banner banner) {
        banner.setId(null);
        bannerRepository.save(banner);
    }

    @Override
    public void update(Banner banner) {
        bannerRepository.save(banner);
    }

    @Override
    public void delete(String id) {
        bannerRepository.deleteById(id);
    }

    @Override
    public Banner get(String id) {
        return bannerRepository.findById(id).orElse(null);

    }

    @Override
    public List<Banner> findAll() {
        return bannerRepository.findAll();
    }

    @Override
    public Page<Banner> query(BannerQuery qo) {
        //bannerRepository 查询只能对所有数据进行分页
        //template 查询不能直接对数据进行分页 间接分页

        Query query = new Query();

        //totalCount 总记录数
        long totalCount = template.count(query, Banner.class);
        if(totalCount == 0){
            return  Page.empty();  //空的分页对象
        }

        //分页参数对象, 参数1 当前页  2 每页显示的条数  3 排序规则  4 排序字段
        PageRequest pageRequest = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");

        query.with(pageRequest);

        List<Banner> list = template.find(query, Banner.class);

        return new PageImpl<>(list, pageRequest, totalCount);
    }

    @Override
    public void saveOrUpdate(Banner banner) {
        if(StringUtils.hasLength(banner.getId())){
            //有id修改
            //参数个数一致等同于全量更新
            this.update(banner);

        }else{
            this.save(banner);
        }
    }

    @Override
    public List<Banner> queryBanner(int type) {
        //必须能显示  按照序号显示前五个
        Pageable pageable = PageRequest.of(0,5, Sort.Direction.ASC,"sequence");

        return bannerRepository.findByStateAndType(Banner.STATE_NORMAL, type, pageable);
    }


}
